<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{ margin:0; padding:0;}
        .contener {
            width: 700px;
            overflow: hidden;
            margin: 0 auto;
        }
        .contener .item {
            float: left;
            margin: 10px 0 5px 10px;
            overflow: hidden;
            position: relative;
            background: #ccc;
        }
        .view{ width:500px;  background-color:#f00; clear:both;margin:auto;}
        .wrap{ clear:both;}
    </style>
</head>
<body>
<div class="contener" id="photo">

</div>
</body>
<script  src="../bower_components/jQuery/dist/jquery.min.js"></script>
<script>
    $(function () {
        var id=1;
        function getData(page) {
            $.getJSON("http://127.0.0.1:1337?page="+page+"&callback=?",function (data) {
                var html='';
                $.each(data,function (idx,item) {
                    html+='<div  class="item" data-width="'+item.tpwidth+'" data-height="'+item.tpheight+'" ><a href="javascript:void(0)" target="_blank"><img _src="'+item.titlepic+'" src="'+item.titlepic+'" ></a></div>'

                })

                $('#photo').append(html);
                flag=true;
//                if(document.documentElement.clientWidth>700){
                    new ePhoto('photo', {containerWidth:700,defaultHeight : 200});
//                }else{
//                    new ePhoto('photo', {containerWidth:500,defaultHeight : 300});
//                }
            })

        }
        getData(1);
        var photo = function(elm,opt) {
            var me = this;
            me.container = typeof elm == 'object' ? elm : document.getElementById(elm);
            me.childrens = $(me.container).find('.item');
            me.opt = {
                defaultHeight : 150,
                margin : parseInt(getComputedStyle(me.childrens[0])['margin-left']) + parseInt(getComputedStyle(me.childrens[0])['margin-right'])
            }
            for (i in opt) me.opt[i] = opt[i];
            me.refleshLayout();
        }
        photo.prototype = {
            _getEveryLineNums : function () {
                var me 	     = this,
                        l 		 = me.childrens.length,
                        curWidth = 0,//计数
                        start    = 0,//计数
                        tmp      = {},
                        r        = [];//返回值
                for (var i = 0 ; i < l; i++) {

                    var o = me._imgMsg(me.childrens[i]);
                    curWidth += me.opt.defaultHeight * o.w/o.h + me.opt.margin;

                    if(curWidth >= me.maxWidth) {
                        tmp = {
                            start : start,
                            end   : i,
                            height: Math.round(me.maxWidth/curWidth * me.opt.defaultHeight)
                        };
                        r.push(tmp);
                        start = i + 1;
                        curWidth = 0;
                    }


                }
                console.log(r);
                return r;
            },
            _imgMsg : function(obj){
                var	o = {
                    w : obj.getAttribute('data-width'),
                    h : obj.getAttribute('data-height')
                }
                return o;
            },
            _sort : function(data) {
                var me = this, max = me.childrens.length - 1;
                if(data.length > 0){
                    for(var i in data) {
                        me._setAttr(data[i].start, data[i].end, data[i].height, false);
                    }
                    if(data[i].end < max){
                        me._setAttr(data[i].end + 1, max, me.opt.defaultHeight, true);
                    }
                } else{
                    me._setAttr(0, max, me.opt.defaultHeight, true);
                }
            },
            _setAttr : function (start, end, h, last) {
                var me = this, item = me.childrens;
                var neW = me._getNeWidth(start, end, h, last, item);
                for(var i in neW) {
                    me.__setAttrBox(neW[i], h, item[i],start,end);
                    me.__setAttrImg(neW[i], h, item[i]);
                }
            },
            __setAttrBox : function(w, h, box,start,end) {
                box.style.width   = w + 'px';
                box.style.height  = h + 'px';
                box.setAttribute("data-row","end"+end);
                box.className+=(" end"+end);
            },
            __setAttrImg : function(w, h, box){
                var me = this;
                var img = box.getElementsByTagName('img')[0];
                baseSize = me._imgMsg(box);//保持图片原有比例
                if(w*h/baseSize.w > baseSize.h) {
                    h = w*baseSize.h/baseSize.w;
                } else {
                    w = baseSize.w*h/baseSize.h;
                }
//                img.src = img.getAttribute('_src') ;
                img.width   = w;
                img.height  = h;
            },
            _getNeWidth : function(s, e, h, last, item){
                var me = this, o = {}, r = [], tmpW = 0, tmpS,
                        dValue = e > s ? e - s + 1 : 1;
                //先算误差
                for(var i = s; i <= e; i++) {
                    o = me._imgMsg(item[i]);
                    r[i] = h/o.h * o.w;
                    tmpW += r[i];
                }
                var gep = !last ? Math.round( (me.maxWidth - tmpW - me.opt.margin * dValue)/dValue ): 0;
                tmpW = 0;
                for(var i in r) {
                    tmpS = Math.floor(r[i] + gep);//把误差分配给前n-1个，最后一个另算
                    if(tmpW + tmpS + me.opt.margin > me.maxWidth || (Number(i) === e && tmpW + tmpS + me.opt.margin <= me.maxWidth && !last)) {
                        tmpS = me.maxWidth - tmpW - me.opt.margin;
                    }
                    r[i] = tmpS;
                    tmpW += tmpS + me.opt.margin;
                }
                return r;
            },
            refleshLayout : function () {
                var me = this;
                me.maxWidth = me.opt.containerWidth;
                me.container.style.width=me.maxWidth+"px";
                me._sort(me._getEveryLineNums());
            }
        };
        window.ePhoto = photo;
        var timer;
        window.onresize=function () {
            var winWidth=document.documentElement.clientWidth;
            clearTimeout(timer);
            timer=setTimeout(function () {
                if(winWidth<=700 && document.getElementById('photo').offsetWidth>500){
                    new ePhoto('photo', {containerWidth:500,defaultHeight : 300});
                }else if(winWidth>700 && document.getElementById('photo').offsetWidth<700){
                    new ePhoto('photo', {containerWidth:700,defaultHeight : 300})
                }
            },500)
        }
        var page=1;
        var flag=true;
        var winH=$(window).height();
        $(document).scroll(function () {
            var scrollTop=$(document).scrollTop();
            var docH=$(document).height();
            if(scrollTop+winH+50>=docH && flag){
                page++;
                id++;
                getData(page);
                flag=false;
            }
        })
        $('#photo').on("click",".item",function () {
            $('.view').remove();
            var row=$(this).data('row').substring(3);
            $('.end'+row).last().after('<div class="view"></div>');
            $('.view').animate({height:"400px"});
            $("html,body").animate({scrollTop:$('.view').offset().top-183});
        })
    })
</script>
</html>